Skip to content

Conversation

squeek502
Copy link
Collaborator

@squeek502 squeek502 commented Sep 14, 2025

This is just clarifying the current behavior of std.mem.replace.

Test case showing the behavior when input/output overlap (adapted from here):

const std = @import("std");

test "mem.replace overlap" {
    var buf: [256]u8 = undefined;
    const original = "Sweet apple cake. Sour crabapple pie.";
    const expected = "Sweet orange cake. Sour craborange pie.";
    buf[0..original.len].* = original.*;
    const str = buf[0..original.len];

    const needed_size = std.mem.replacementSize(u8, str, "apple", "orange");
    const output = buf[0..needed_size];
    _ = std.mem.replace(u8, str, "apple", "orange", output);
    try std.testing.expectEqualStrings(expected, output);
}
====== expected this output: =========
Sweet orange cake. Sour craborange pie.␃

======== instead found this: =========
Sweet orangeeeeeeeeeeeeeeeeeeeeeeeeeee�␃

======================================
First difference occurs on line 1:
expected:
Sweet orange cake. Sour craborange pie.
            ^ ('\x20')
found:
Sweet orangeeeeeeeeeeeeeeeeeeeeeeeeeee�
            ^ ('\x65')

@jeffective
Copy link
Contributor

is this not a usecase for the noalias keyword? Unfortunately its undocumented in the langref.

@ProkopRandacek
Copy link
Contributor

It would be cool to assert that they dont overlap

Copy link
Member

@andrewrk andrewrk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, this is certainly an improvement over status quo.

However, @jeffective is correct that it would be even better to document that they must not overlap with the noalias keyword. @ProkopRandacek is also correct that it would be nice if the language could help assert that property, which it currently does not.

The relevant issue there is #476

@andrewrk andrewrk merged commit c330d2b into ziglang:master Sep 18, 2025
25 of 26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants